package com.flute.haflute.slave;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.rmi.RemoteException;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.flute.haflute.common.ClusterConstants.COMMAND;
import com.flute.haflute.jobbox.base.RunProcessInterface;
import com.flute.haflute.jobbox.common.CloudContext;
import com.flute.haflute.jobbox.common.RunProcessLauncher;
import com.flute.haflute.jobbox.communication.ChildCommunicationService;
import com.flute.haflute.jobbox.communication.ClientService2Server;
import com.flute.haflute.master.MasterCommandHandler;
import com.flute.haflute.tools.ClusterUtils;

/**
 * 作业子节点侦听Agent代理命令和消息的接口
 * 
 * @see MasterCommandHandler
 * 
 */
public class ChildCommandHandler extends Thread {
	
	private static Logger logger = LoggerFactory
			.getLogger(ChildCommandHandler.class);

	public ChildCommandHandler(String name) {
		super(name);
	}

	public void run() {
		BufferedReader reader = new BufferedReader(new InputStreamReader(
				System.in));
		String line;
		try {
			while ((line = reader.readLine()) != null) {
				// 收到切换至新的作业节点的消息
				logger.info("received new message : {}", line);
				if (line.startsWith(COMMAND.JOB_NEW_CENTER)) {
					String newMaster = line.replace(COMMAND.JOB_NEW_CENTER, "");
					logger.info("received new Master is {}", newMaster);
					boolean needReconnect = true;
					if (newMaster.equalsIgnoreCase(CloudContext
							.getCloudMaster())) {
						needReconnect = isMasterLost();
					}
					if (needReconnect) {
						connect2NewMaster(newMaster);
						reInstallChildContext();
					}
				}
				// 收到集群关闭消息
				else if (line.startsWith(COMMAND.SHUTDOWN)) {
					logger.info("Received exit command, Child will exit");
					ClusterUtils.exitGracefully();
				}
			}
		} catch (IOException e) {
			logger.error("", e);
		}
	}

	/**
	 * @return true connection lost; false connection available;
	 */
	private boolean isMasterLost() {
		try {
			ClientService2Server service = new ChildCommunicationService()
					.getMasterNotifier();
			if (service.isAlive())
				;
			return false;
		} catch (RemoteException e) {
			logger.info("checkMasterStatus : Not Active", e);
			return true;
		}
	}

	private void reInstallChildContext() {
		List<RunProcessInterface> processList = RunProcessLauncher
				.getRunProcessList();
		for (RunProcessInterface process : processList) {
			try {
				process.restart();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}

	private void connect2NewMaster(String newMaster) {
		CloudContext.setCloudMaster(newMaster);
		ChildCommunicationService.initConnection2NewMaster();
	}
}
